package service.serviceImpl;

import dao.ClassroomMapper;
import dao.ReservationMapper;
import entity.Building;
import entity.Classroom;
import entity.example.ClassroomExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.ClassroomService;

import java.util.*;

/***
 * Author: Mr.Zhao, Time: 2019/5/24/17:21
 * Description:
 */
@Service
public class ClassroomServiceImpl implements ClassroomService {
    private static final Logger logger = LoggerFactory.getLogger(ClassroomServiceImpl.class);
    @Autowired
    ClassroomMapper classroomDao;
    @Autowired
    ReservationMapper reservationDao;

    public List<Classroom> selectFree(Date startTime, Date endTime, Integer buildingId) {
        ClassroomExample classroomExample = new ClassroomExample();
        ClassroomExample.Criteria criteria = classroomExample.createCriteria();

//        criteria.

        return null;
    }

    public List<Building> selectFree(Date startTime, Date endTime) {
        List<Classroom> classrooms = classroomDao.selectFree(startTime, endTime);
        logger.debug("classroomList: " + classrooms);

        return classrooms2buildings(classrooms);

    }

    @Override
    public List<Building> selectAll() throws Exception {
        List<Classroom> classrooms = classroomDao.selectAll();
        return classrooms2buildings(classrooms);
    }

    /**
     * 将多对一(classrooms->building)转换为一对多(building->classrooms)
     *
     * @param classrooms 教室列表
     * @return 教学楼列表
     */
    private List<Building> classrooms2buildings(List<Classroom> classrooms) {
        //将一对多转为多对一
        List<Building> buildings = new ArrayList<>();
        for (Classroom classroom : classrooms) {
            Building cbuilding = classroom.getBuilding();
            // 能用contains的理由是building中覆写了equals方法
            if (!buildings.contains(cbuilding)) {
                buildings.add(cbuilding);
            }
            Building retBuilding = buildings.get(buildings.size() - 1);

            if (retBuilding.getClassrooms() == null) {
                List<Classroom> classrooms2 = new ArrayList<>();
                classrooms2.add(classroom);
                retBuilding.setClassrooms(classrooms2);
            } else {
                retBuilding.getClassrooms().add(classroom);
            }
            classroom.setBuilding(null);
        }
        return buildings;
    }
}
